<template>
  <div>
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <Spin size="large" />
      <p style="margin-top: 16px">加载中...</p>
    </div>
    
    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <Alert message="加载失败" description="无法加载该组件" type="error" show-icon />
      <a-button @click="reload" style="margin-top: 16px">重试</a-button>
    </div>
    
    <!-- 组件内容 -->
    <component v-else :is="resolvedComponent" />
  </div>
</template>

<script setup>
import { ref, defineAsyncComponent, watch } from 'vue';
import { Alert, Spin } from 'ant-design-vue';

const props = defineProps({
  // 组件对象或异步组件函数
  component: {
    type: [Function, Object],
    required: true
  }
});

const loading = ref(false);
const error = ref(false);
const resolvedComponent = ref(null);

// 加载组件的函数
const loadComponent = () => {
    console.log(props.component)
  loading.value = true;
  error.value = false;
  resolvedComponent.value = null;
  
  try {
    // 检查是否是函数但不是组件构造函数
    if (typeof props.component === 'function' && !props.component.prototype) {
        console.log(1)
      // 处理异步组件
      const asyncComponent = defineAsyncComponent({
        loader: () => props.component().catch(err => {
          console.error('组件加载失败:', err);
          error.value = true;
          loading.value = false;
          // 返回一个占位组件
          return { render: () => null };
        }),
        loadingComponent: {
          template: `
            <div class="loading-container">
              <Spin size="large" />
              <p style="margin-top: 16px">加载中...</p>
            </div>
          `
        },
        delay: 200,
        timeout: 30000
      });
      resolvedComponent.value = asyncComponent;
    } else {
        console.log(2)
      // 处理普通组件
      resolvedComponent.value = props.component;
      loading.value = false;
    }
  } catch (err) {
    console.error('组件加载失败:', err);
    error.value = true;
    loading.value = false;
  }
};

// 监听组件变化
watch(
  () => props.component,
  () => {
    loadComponent();
  },
  { immediate: true }
);

// 重新加载组件
const reload = () => {
  loadComponent();
};
</script>

<style scoped>
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
}

error-container {
  padding: 24px;
  text-align: center;
}
</style>